<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>与其他异步处理方法的比较</title>
</head>
<body>
    <h1>与其他异步处理方法的比较</h1>

    <script>
        // 回调函数
        function fetchDataCallback(callback) {
            setTimeout(() => {
                callback(null, '数据');
            }, 1000);
        }

        fetchDataCallback((err, result) => {
            if (err) {
                console.error(err);
                return;
            }
            console.log(result);
        });

        // Promise
        function fetchDataPromise() {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    resolve('数据');
                }, 1000);
            });
        }

        fetchDataPromise()
            .then(result => console.log(result))
            .catch(err => console.error(err));

        // Generator函数
        function* fetchDataGenerator() {
            try {
                const result = yield fetchDataPromise();
                console.log(result);
            } catch (err) {
                console.error(err);
            }
        }

        function run(generator) {
            const iter = generator();
            function next(data) {
                const result = iter.next(data);
                if (result.done) return;
                result.value.then(data => next(data));
            }
            next();
        }

        run(fetchDataGenerator);

        // async/await
        async function fetchDataAsync() {
            try {
                const result = await fetchDataPromise();
                console.log(result);
            } catch (err) {
                console.error(err);
            }
        }

        fetchDataAsync();

        // 链式调用比较
        // Promise方式
        function chainPromise() {
            return fetchDataPromise()
                .then(result1 => {
                    return fetchDataPromise().then(result2 => {
                        return [result1, result2];
                    });
                });
        }

        // async/await方式
        async function chainAsync() {
            const result1 = await fetchDataPromise();
            const result2 = await fetchDataPromise();
            return [result1, result2];
        }
    </script>
</body>
</html> 